package com.godlei.security.service.impl;


import com.godlei.security.entity.Users;
import com.godlei.security.mapper.UserMapper;
import com.godlei.security.service.IUserDetailService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UsersDetailServiceImpl
 * @Description 用户表业务层实现
 * @Author 高达磊
 * @Date 2021/12/22-14:13
 * @Version 1.0
 */
@Service
public class UsersDetailServiceImpl implements IUserDetailService {

    @Resource
    private UserMapper userMapper;

    /**
     * 通过用户名查询用户信息
     * @param username 用户名
     * @return 用户信息（包含角色信息）
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Users user = userMapper.findOneByUserName(username);

        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<SimpleGrantedAuthority> grantedAuthorityList = new ArrayList<>();
        user.getAuthoritiesList().forEach(authorities -> {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authorities.getAuthority());
            grantedAuthorityList.add(simpleGrantedAuthority);
        });

        return new User(user.getUserName(), user.getPassword(), grantedAuthorityList);
    }
}
